<template>
    <div class="map">
        <div ref="chartDom" class="chart"></div>         
    </div>
</template>

<script setup>
import {onMounted, ref,computed,onUnmounted,watch,onBeforeUnmount} from "vue"
import * as echarts from 'echarts'
import 'echarts-gl';
import chinaJson from '../../assets/map/china.json';
import { sheng } from '../../assets/map/china.js';
import { rem2px } from "../../utils/scale"

//随机数据
const randValue= (number=100) => {
  return Math.round(Math.random() * number)
}

const provinceList = sheng.map(item=>item.name2)
const barProvince = [...provinceList] // 复制一份，避免原数组被改
  .sort(() => Math.random() - 0.5)      // 打乱顺序
  .slice(0, 6);                          // 抽前5个

//   console.log(randomSubset)


// 只选几个省份举例，也可以全选
// const barData =barProvince
//   .map(name => {
//     const province = sheng.find(p => p.name2 === name)
//     return {
//       name: name.replace('省', '').replace('自治区', '').replace('市', ''), // echarts 中显示的是简称
//       value: province ? [...province.coordinate, randValue()] : [0, 0, 0],
//       xian: randValue(5000),
//       fu: randValue(5000),
//     }
//   })
const barData = barProvince.map(name => {
  const province = sheng.find(p => p.name2 === name)
  const xian = randValue(5000)
  const fu = randValue(5000)

  // 加微小经纬度偏移，避免 label 重叠
  const offsetLng = (Math.random() - 0.5) * 0.5 // 经度偏移 ±0.25°
  const offsetLat = (Math.random() - 0.5) * 0.5 // 纬度偏移 ±0.25°

  return {
    name: name.replace('省', '').replace('自治区', '').replace('市', ''),
    value: province
      ? [province.coordinate[0] + offsetLng, province.coordinate[1] + offsetLat, xian + fu]
      : [0, 0, 0],
    xian,
    fu
  }
})

const scatterData = barData.map(item => ({
  name: item.name,
  value: [item.value[0], item.value[1], 0] // z 轴设为 0，仅用于 label
}))
// const scatterData = sheng.map(item=>({
//     name:item.name2,
//     value:[...item.coordinate,0]
// }))

const chartDom = ref(null)
let myChart=null
const chartOption=ref(null)

// 注册地图
echarts.registerMap('china', chinaJson);

// 配置项
const mapOption = {
    geo3D: {
        map: 'china', // 或其他地图名
        shading: 'color',
        itemStyle: {
            color: 'rgba(41,116,236,.3)',
            // color: 'rgba(15,53,192)',
            borderColor: '#fff',
            borderWidth: .6,
        },
        regionHeight:5,
        light: {
            main: {
                intensity: 1,
                shadow: true,
                shadowQuality: 'high',
            },
            ambient: {
                intensity: 0.3,
            },
        },
        viewControl: {
            center: [0, 0, -10], 
            alpha:65,
            beta:0,
            distance: 80  // 缩小此值放大地图，默认约为 100-120
        },
    },
    series: [
        {
            // type: 'bar3D',
            type: 'scatter3D',
            coordinateSystem: 'geo3D',
            symbolSize: 10,
            shading: 'realistic',
            label: {
                show: true,
                formatter: function (params) {
                    const data = params.data;
                    return `${params.name}\n\n险:${data.xian}\n\n服:${data.fu}`;
                },
                color: '#fff',
                fontSize:rem2px(1.2),
                backgroundColor: 'rgba(0,0,0)',
                padding: [8,9],
                // offset: [0, 50], // 向上偏移 20 像素
            },
            itemStyle: {
                color: '#43ff38' // 自定义柱颜色
            },
            data: barData
        },
        // {
        //     type: 'scatter3D',
        //     coordinateSystem: 'geo3D',
        //     symbolSize: 0,
        //     label: {
        //         show: true,
        //         formatter: function (params) {
        //             return params.name;
        //         },
        //         fontSize: 14,
        //         color: '#fff',
        //         offset: [0, 0],
        //         // offset: [-10, 0], // 向上偏移 20 像素
        //     },
        //     data: scatterData
        // }
        ]

  };

const useMapOtion=()=>{
  chartOption.value = mapOption

  if (chartDom.value) {
    myChart = echarts.init(chartDom.value); 
    myChart.setOption(chartOption.value);
  }
//   console.log(myChart.getModel().getComponent('geo3D').coordinateSystem.regions.map(r => r.name));

}

// 初始化图表
onMounted(() => {
  if (chartDom.value) {
    myChart = echarts.init(chartDom.value);
  
    useMapOtion()
    
    const observer = new ResizeObserver(() => {
      myChart?.resize();
    });
    observer.observe(chartDom.value);

    onBeforeUnmount(() => {
      observer.disconnect(); // 停止监听
      myChart?.dispose();
    });
  }

});

</script>

<style lang="scss" scoped>
.map{
    width: 100%;
    height: calc(100% - 8.6rem - 2.4rem );
    // border: 1px solid red;
    display: flex;

}
.chart{
    width: 100%;
    height: 60rem;
    // border: 1px solid red;
    // background: url('@/assets/img/map.png') no-repeat  ;
    // background-size: cover; // 或 contain
    // background-position: 80% 50%;
}
</style>